package com.siteseat.common.json;

import java.io.IOException;

import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.deser.StdDeserializer;

import com.siteseat.common.exception.InternalException;
import com.siteseat.common.security.Permission;

public class PermissionDeserializer extends StdDeserializer<Permission> {

  /**
   * 
   */
  public PermissionDeserializer() {
    super( Permission.class );
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public Permission deserialize( JsonParser jp, DeserializationContext ctxt ) throws IOException, JsonProcessingException {
    String txt = jp.getText();
    Permission r = Permission.forName( txt );
    if( r == null ) {
      Integer code;
      try {
        code = Integer.valueOf( Integer.parseInt( txt ) );
      }catch( NumberFormatException e ) {
        throw new InternalException( "Unknown permssion code or name: " + txt );
      }
      r = Permission.forCode( code );
      if( r == null ) {
        throw new InternalException( "Unknown permssion code: " + txt );
      }
    }
    return r;
  }

}
